//
//  LLGStatuseListViewModel.swift
//  Weibo30LLG
//
//  Created by 李龙 on 16/8/12.
//  Copyright © 2016年 lilong. All rights reserved.
//

import UIKit

//获取微博数据的viewModel 对应tableView
class LLGStatuseListViewModel: NSObject {

    
    //数据源
    lazy var dataList: [LLGStatuseViewModel] = [LLGStatuseViewModel]()
    // MARK: --加载数据
    func loadData(isPullup: Bool, callBack: (isSuccess: Bool, message: String) -> ()) {
        
        //上拉加载请求参数
        var maxId: Int64 = 0
        
        var sinceId: Int64 = 0
        
        //判断是上拉刷新
        if isPullup {
            
            maxId = dataList.last?.statuse?.id ?? 0
            //去除0
            if maxId > 0 {
            
                maxId -= 1
            }
        } else {
        
            sinceId = dataList.first?.statuse?.id ?? 0
            
        }
        
        //tip文字
        var result = "没有加载到最新的微博数据"
        
        //通过accessToken获取用户关注数据
        LLGNetworkTools.sharedTools.requestStatuses(LLGUserAccountViewModel.sharedUserAccount.accessToken!, maxId: maxId, sinceId: sinceId) { (response, error) -> () in
            if error != nil {
                
                print(error)
                callBack(isSuccess: false, message: result)
                return
            }
            
            //判断是否为字典
            guard let dict = response as? [String: AnyObject] else {
                print("不是字典")
                callBack(isSuccess: false, message: result)
                return
            }
            
            //判断是否为存有字典的数组
            guard let dictArr = dict["statuses"] as? [[String: AnyObject]] else {
                callBack(isSuccess: false, message: result)
                return
            }
            
            //可变数组
            var arrayM = [LLGStatuseViewModel]()
            
            //遍历数组,字典转模型,存储到可变数组
            for value in dictArr {
                
                let statuse = LLGStatuses(dict: value)
                let viewModel = LLGStatuseViewModel(statuse: statuse)
                
                arrayM.append(viewModel)
            }
            
//            //设置数据源,更新数据
//            self.dataList = arrayM
            //判断是否是上拉加载
            if isPullup {
                //添加到数组后面
                self.dataList.appendContentsOf(arrayM)
            } else {
                //查到数组最前面
                self.dataList.insertContentsOf(arrayM, at: 0)
            }
            
//              //延时两秒回调
//                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(),{ () -> Void in
//                            callBack(isSuccess: true)
//                        })
            
            if arrayM.count > 0 {
            
                result = "加载了\(arrayM.count)条数据"
            }
//            
            callBack(isSuccess: true, message: result)
        }
    }
}

    

